<?php
// +----------------------------------------------------------------------
// | Description: 用户
// +----------------------------------------------------------------------
// | Author: linchuangbin <linchuangbin@honraytech.com>
// +----------------------------------------------------------------------

namespace app\admin\model;

use think\Db;
use app\admin\model\Common;
use com\verify\HonrayVerify;

class Firstpass extends Common
{

    /**
     * 为了数据库的整洁，同时又不影响Model和Controller的名称
     * 我们约定每个模块的数据表都加上相同的前缀，比如微信模块用weixin作为数据表前缀
     */
    protected $name = 'apply';
    protected $createTime = 'time';
    protected $updateTime = false;
    protected $autoWriteTimestamp = DATETIME;
    // protected $insert = [
    //     'status' => 1,
    // ];

 
    /**
     * [getDataList 列表]
     * @AuthorHTL 湛慧平
     * @DateTime  2017-02-10T22:19:57+0800
     * @param     [string]                   $keywords [关键字]
     * @param     [number]                   $page     [当前页数]
     * @param     [number]                   $limit    [t每页数量]
     * @return    [array]                             [description]
     */
    public function getDataList($keywords, $page, $limit, $valuedate, $os = '')
    {
        $map = [];
        if($valuedate)
        {
          $valuedate = substr($valuedate,0,10);
          $valuedate = date('Y-m-d',strtotime("$valuedate +1 day"));
          $map['time'] = ['like', '%'.$valuedate.'%'];
        }
        if ($keywords) {
            $map['phone|order_number|name'] = ['like', '%'.$keywords.'%'];
        }
        if($os)
        {
            $map['os'] = $os;
        }
        if(""!=$status)
        {
            // $map['status'] = $status;
        }
        
        $map1['status'] = 1;
        $dataCount = $this->where($map)->where($map1)->where('check2_aid is null')->count('id');
        
        $list = $this
            ->where($map);
        // 若有分页
        if ($page && $limit) {
            $list = $this->page($page, $limit);
        }
        
       $list = $list->field('id,status,uid,time,money,period,order_number,check_time,check_aid,check2_aid,name,credit_rate,service_rate,procedure_rate,appoint_time,mobile_type,os')
                    ->where($map1)
                    ->where('check2_aid is null')
                    ->order('status asc, check2_aid asc, id desc')
                    ->select();
       
        foreach($list as $key=>$value)
        {
            $maps['id'] = $value['check_aid'];

            $list[$key]['user_admin1'] = Db::name('admin_user')->field('username')->where($maps)->find();
            $list[$key]['admin_uid'] = $admin_uid;

            // 多次借款
            $mapu['uid'] = $value['uid'];
            $count = $this->where($mapu)->where('id','<=',$value['id'])->count();
            if($count>=2)
            {
                
                $find = $count-2;
                $selectdata = $this->where($mapu)->select();
                $happen = $selectdata[$find]['status'];
                $list[$key]['happen'] = $happen;  
                
            }
            

            $list[$key]['counts'] = $count;
        }

        $data['list'] = $list;
        $data['dataCount'] = $dataCount;
        return $data;
    }

     /**
     * [claim 修改状态]
     * @湛慧平
     * @DateTime  2017-08-12
     * @param     string                 
     * @return    [array]
     */
    public function claim($id,$admin_uid,$uid)
    {
       $map['id'] = $id;
       $info = $this->field('check2_aid')->where($map)->find();
       if($info['check2_aid'])
       {
         return $data = ['code'=>'error','message'=>'已经被认领'];
       }
       
       $this->startTrans();
       try{

            $nowdate = date('Y-m-d',time());
            $mapseq['nowdate'] = ['like','%'.$nowdate.'%'];
            $infocount = Db::name('claim_seq')
                         ->where('auth_admin',1)
                         ->where('admin_id',$admin_uid)
                         ->where($mapseq)
                         ->count();
            $claim_date = ['uid'=>$uid,'apply_id'=>$id,'nowdate'=>$nowdate,'auth_admin'=>1,'seq'=>$infocount+1,'admin_id'=>$admin_uid];
            Db::name('claim_seq')->insert($claim_date);
            
            $second_claim_date = date('Y-m-d H:i:s',time());
            $data = array('check2_aid'=>$admin_uid,'second_claim_date'=>$second_claim_date);
            $info = $this->save($data, ['id' => $id]);  //添加至apply表中
            // 提交事务
            $this->commit(); 
            return $data = ['code'=>'success','message'=>'认领成功'];
            // 提交事务
        $this->commit();
       }catch(\Exception $e)
       {
        $this->rollback();
        return false;
       }
       
    }
   
    /**
     * [getDataById 根据主键获取详情]
     * @linchuangbin
     * @DateTime  2017-02-10T21:16:34+0800
     * @param     string                   $id [主键]
     * @return    [array]
     */
    public function getDataById($id = '')
    {
        $data=$this
            ->field('id,money,period,credit_rate,service_rate,procedure_rate,overdue_rate')
            ->where('id',$id)
            ->find();
        return $data;
    }
    /**
     * [createData 新建]
     * @linchuangbin
     * @DateTime  2017-02-10T21:19:06+0800
     * @param     array                    $param [description]
     * @return    [array]                         [description]
     */
    public function createData($param)
    {

        // // 验证
        // $validate = validate($this->name);
        // if (!$validate->check($param)) {
        //     $this->error = $validate->getError();
        //     return false;
        // }
        try {
            $this->data($param)->allowField(true)->save();
            return true;
        } catch(\Exception $e) {
            $this->error = '添加失败';
            return false;
        }
    }    

    /**
     * [updateDataById 编辑]
     * @linchuangbin
     * @DateTime  2017-02-10T21:24:49+0800
     * @param     [type]                   $param [description]
     * @param     [type]                   $id    [description]
     * @return    [type]                          [description]
     */
    public function updateDataById($param, $id)
    {
        $checkData = $this->get($id);
        if (!$checkData) {
            $this->error = '暂无此数据';
            return false;
        }

        // // 验证
        // $validate = validate($this->name);
        // if (!$validate->check($param)) {
        //     $this->error = $validate->getError();
        //     return false;
        // }

        try {
            $this->allowField(true)->save($param, [$this->getPk() => $id]);
            return true;
        } catch(\Exception $e) {
            $this->error = '编辑失败';
            return false;
        }
    }


    //批量认领
    public function batchclaim($param)
    {

      $data = $param['multipleSelection'];
      $admin_uid = $GLOBALS['userInfo']['id'];
      
      $arr =array();
      foreach($data as $key=>$value)
      {
        $arr[] = $value['id'];
        $arruid[] = $value['uid'];
      }
     
      $this->startTrans();
      try{
        
        $count = count($arr);
        for($i=$count-1;$i>=0;$i--)
        {
            $id = $arr[$i];
            $uid = $arruid[$i];
            $nowdate = date('Y-m-d',time());
            $mapseq['nowdate'] = ['like','%'.$nowdate.'%'];
            $infocount = Db::name('claim_seq')
                         ->where('auth_admin',1)
                         ->where('admin_id',$admin_uid)
                         ->where($mapseq)
                         ->count();
            $claim_date = ['uid'=>$uid,'apply_id'=>$id,'nowdate'=>$nowdate,'auth_admin'=>1,'seq'=>$infocount+1,'admin_id'=>$admin_uid];
            Db::name('claim_seq')->insert($claim_date);
        }
         
        $where['id'] = array('in',$arr);
        $second_claim_date = date('Y-m-d H:i:s',time());
        $data = array('check2_aid'=>$admin_uid,'second_claim_date'=>$second_claim_date);
        $info = $this->save($data,$where);
          // 提交事务
        $this->commit(); 
        return true;   
      } catch (\Exception $e) {
          // 回滚事务
        $this->rollback();
        $this->error = '删除失败';
        return false;
      }
    }

}